package com.mj.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class MyInterceptor implements HandlerInterceptor{
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        boolean flag = true;
        //response.sendRedirect("login.jsp");这个是重定向如果这里进行跳转的话，拦截器就失去了效果，不会执行下面的return
        //request.getRequestDispatcher("login.jsp").forward(request,response);这个是转发，可以传值，重定向不可以传值
        HttpSession session = request.getSession();
        if (session.getAttribute("admin")==null){
            //flag = false;
            System.out.println("已被拦截，无法通过拦截器");//判断是否登录，如果没有登录则直接跳转到登录界面，如果登录后，则可以返回
            request.getRequestDispatcher("login.jsp").forward(request,response);//这个是转发，可以传值，重定向不可以传值
        }
        //return true;
        return flag;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView mv) throws Exception {
        System.out.println("拦截器处理后");
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {
        System.out.println("拦截器最后执行");
    }
}
